﻿using System;
using System.Collections;
using System.Net;
using System.Collections.Generic;

namespace GT
{
    public static partial class Extensions
    {
        public static float FastDivision(this int dividend, int divisor)
        {
            return dividend * (1f / divisor);
        }

        public static int FastIntDivision(this int dividend, int divisor)
        {
            return (int)(dividend * (1f / divisor));
        }

        public static IPAddress FromCidr(this int cidr)
        {
            if (cidr < 0 || cidr > 128)
                throw new ArgumentOutOfRangeException("cidr", "CIDR value cannot be less than 0 or greater than 128");

            BitArray ret;
            if (cidr > 32)
                ret = new BitArray(128);    // IPv6
            else
                ret = new BitArray(32);     // IPv4

            ret.Length.IterateIndex(i =>
            {
                ret[i] = (i < cidr);
            });

            byte[] bytes = new byte[ret.Length > 32 ? 16 : 4];
            ret.CopyTo(bytes, 0);
            return new IPAddress(bytes);
        }

        public static bool HasValue(this int enumVal, int val)
        {
            return ((enumVal & val) == val);
        }

        public static void IterateIndex(this int repeatCount, Action<int> action)
        {
            for (int i = 0; i < repeatCount; i++)
            {
                action(i);
            }
        }

        public static void IterateCount(this int repeatCount, Action<int> action)
        {
            for (int i = 1; i <= repeatCount; i++)
            {
                action(i);
            }
        }

    }
}
